package com.example.controller.admin;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.Constants;
import com.example.common.Result;
import com.example.entry.User;
import com.example.entry.dto.UserDto;
import com.example.service.IUserService;
import com.example.util.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/*
* 用户后台管理控制器
* */

@RequestMapping("/admin/user")
@RestController
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /*
    * 登录
    * */
    @PostMapping("/login")
    public Result login(@RequestBody UserDto userDto){
//        调用hutool工具类判断账号密码是否为空
        if(StrUtil.isBlank(userDto.getUsername()) || StrUtil.isBlank(userDto.getPassword())){
            return Result.error(Constants.CODE_600, "请输入用户名和密码");
        }
        UserDto dto = userService.login(userDto);
        return Result.success("登录成功",dto);
    }

    /*
    * 验证token
    * */
    @GetMapping("/check-token")
    public Boolean checkToken(HttpServletRequest request){
        String token = request.getHeader("token");
        return TokenUtils.checkToken(token);
    }

//    注册
    @PostMapping("/register")
    public Result register(@RequestBody User user){
        return userService.userRegister(user);
    }

    // 根据id查询信息
    @GetMapping("/user-id/id={id}")
    public Result getUserOne(@PathVariable Integer id){
        String stringId = stringRedisTemplate.opsForValue().get(id.toString()); // 查询redis是否存在key

        if(StringUtils.isEmpty(stringId)){
            User byId = userService.getById(id);// 查找用户
            stringRedisTemplate.opsForValue().set(id.toString(), JSON.toJSONString(byId)); // 存储数据在redis，id为key
            stringRedisTemplate.expire(id.toString(), 24, TimeUnit.HOURS); // 存在redis的有效期为24小时
            return Result.success("success", byId);
        }
        JSONObject object = JSON.parseObject(stringId);
        return Result.success(object);
    }

    /*
    * 根据id进行删除
    * */
    @GetMapping("/delete-user/id={id}")
    public Result deleteUserInfo(@PathVariable Integer id) {
        stringRedisTemplate.delete(id.toString()); // 数据发生改变，删除redis缓存
        userService.removeById(id);
        return Result.success("删除成功");
    }

    /*
     * 批量删除
     * */
    @PostMapping("/batchd_delete")
    public Result batchDelete(@RequestBody List<Integer> ids){
        userService.removeBatchByIds(ids);
        return Result.success("删除成功");
    }

    /*
    * 修改或保存信息
    * */
    @PostMapping("/update")
    public Result updateOrSaveUser(@RequestBody User user){
        stringRedisTemplate.delete(user.getId().toString()); // 数据发生改变，删除redis缓存
        userService.saveOrUpdate(user);
        return Result.success("success");
    }

    /*
    * 分页查询
    * */
    @GetMapping("/page")
    public Result getPageUser(@RequestParam Integer pageNum,
                              @RequestParam Integer pageSize,
                              @RequestParam(defaultValue = "1") Integer status,
                              @RequestParam(defaultValue = "") String username,
                              @RequestParam(defaultValue = "") String phone,
                              @RequestParam(defaultValue = "") String nickname){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 排除指定字段，不需要查询密码
        queryWrapper.select(User.class,i -> !i.getColumn().equals("password"));
        // 根据id进行降序排序
        queryWrapper.orderByDesc("id");
        // 查询管理员和普通用户
        if(!"".equals(status)){
            queryWrapper.like("status", status);
        }
        // 根据条件进行模糊查询
        if(!"".equals(username)){
            queryWrapper.like("username", username);
        }
        if(!"".equals(phone)){
            queryWrapper.like("phone", phone);
        }
        if(!"".equals(nickname)){
            queryWrapper.like("nickname", nickname);
        }
        // 分页构造器
        Page<User> userPage = userService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.success(userPage);
    }
}
